
import com.lijin.download.DownBean;
import com.lijin.download.DownLoadUtls;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 *  批量下载文件
 */
public class DownBatch {

    /**
     *  下载文件
     * @param params
     */
    public void down(String params []) throws IOException {
        if(params.length < 2){
            throw new RuntimeException("参数依次为：m3u8文件所在的本地目录、保存文件的路径!");
        }
        String m3u8ParentPath = params[0];
        String savePath = params[1];

        if(!com.lijin.download.FileUtils.validatePathExist(m3u8ParentPath)){
            throw new RuntimeException("m3u8本地父目录不存在");
        }
        Collection<File> m3u8s = FileUtils.listFiles(new File(m3u8ParentPath), new String[]{"m3u8"}, false);
        if(m3u8s.isEmpty()){
            throw new RuntimeException("m3u8本地父目录没有查询到m3u8文件");
        }
        savePath = com.lijin.download.FileUtils.notExist2Create(savePath, "c:/download");
        ArrayList<DownBean> beans = new ArrayList<>();
        for (File m3u8:m3u8s) {
            String content = FileUtils.readFileToString(m3u8, "UTF-8");
            Set<String> downUrls = com.lijin.download.FileUtils.resolveUrl(content);
            if(downUrls.isEmpty()){continue;}
            String firstUrl = downUrls.iterator().next();
            beans.add(new DownBean(m3u8.getAbsolutePath(), downUrls, savePath, FilenameUtils.getExtension(firstUrl), FilenameUtils.getBaseName(m3u8.getName())));
        }
        ThreadPoolExecutor newFixedThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(12);
        for (int i = 0; i < beans.size() ; i++) {
            DownBean bean = beans.get(i);
            Collection<String> urls = bean.getUrls();
            System.err.printf("当前下载文件名称为：%s \n",bean.getSaveFileName());
            for (String url:urls) {
                newFixedThreadPool.execute(()->{
                    DownLoadUtls.down(url,bean.getSavePath(),bean);
                });
            }
            newFixedThreadPool.shutdown();
            while(!newFixedThreadPool.isTerminated()){}
            LinkedList<File> files = (LinkedList)FileUtils.listFiles(new File(bean.getSavePath()), new String[]{bean.getExtension()}, false);
            //Collections是一个在Collection上操作的工具类。可以实现对集合元素的排序
            Collections.sort(files,(File o1, File o2) ->{
                return o1.getName().compareTo(o2.getName());
            });
            com.lijin.download.FileUtils.merge(
                    files,
                    bean.getMergeNames(),
                    new File(bean.getSavePath(),new StringBuffer(bean.getSaveFileName()).append(".").append(bean.getExtension()).toString()),
                    true
            );
            if(i != beans.size()-1){
                newFixedThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(12);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new DownBatch().down(args);
    }
}